package com.tanhua.admin.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存生成的验证码
     * @param uuid
     * @param code
     */
    public void saveCode(String uuid, String code) {
        String key = Constants.CAP_CODE + uuid;
        // 缓存验证码，10分钟后失效
        stringRedisTemplate.opsForValue().set(key,code, Duration.ofMinutes(10));
    }

    /**
     * 用户登陆
     * @param username
     * @param password
     * @param verificationCode
     * @param uuid
     * @return
     */
    public Map<String, String> login(String username, String password, String verificationCode, String uuid) {

        String key = Constants.CAP_CODE + uuid;
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(redisCode)) {
            throw new BusinessException("验证码已失效");
        }

        if(!StringUtils.equalsIgnoreCase(redisCode, verificationCode)) {
            throw new BusinessException("验证码不正确");
        }

        stringRedisTemplate.delete(key);
        String md5Password = DigestUtils.md5Hex(password);
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Admin::getUsername, username).eq(Admin::getPassword, md5Password);
        Admin admin = adminMapper.selectOne(queryWrapper);

        if(null == admin) {
            throw new BusinessException("账号或密码错误");
        }

        String token = JwtUtils.createToken(admin.getId(), admin.getUsername());
        String tokenKey = Constants.TOKEN + token;
        String adminJSONStrng = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(tokenKey, adminJSONStrng, 30L, TimeUnit.MINUTES);

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("token", token);
        return resultMap;
    }

    /**
     * 用户登出
     */
    public void logout(String token) {
        String tokenKey = "TOKEN_" + token;
        stringRedisTemplate.delete(tokenKey);
    }
}
